package com.example.everying.controller.official;/*
 * 项目名称: everything
 * 文件名: OfficialNoticeController
 * 作者: 张泽阳
 * 日期: 2025/6/19
 * 描述:
 */

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.everying.annotation.WebLog;
import com.example.everying.context.UserContext;
import com.example.everying.model.dto.official.OfficialNotificationDto;
import com.example.everying.model.dto.system.SysNotificationDto;
import com.example.everying.model.entity.official.OfficialNotification;
import com.example.everying.model.entity.system.SysNotification;
import com.example.everying.model.vo.officialNotice.FilePathVo;
import com.example.everying.model.vo.user.UserInfoVo;
import com.example.everying.service.chat.WebSocketBroadcastService;
import com.example.everying.service.official.OfficialNotificationService;
import com.example.everying.service.system.SysNotificationService;
import com.example.everying.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@Api(tags = "系统通知")
@RequestMapping("/official/notice")
@RequiredArgsConstructor
public class OfficialNoticeController {
    @Autowired
    private WebSocketBroadcastService webSocketBroadcastService;
    @Autowired
    private OfficialNotificationService officialNotificationService;

    @Value("${activityPath}")
    private String activityPath;

    @Value("${activityUrlPrefix}")
    private String activityUrlPrefix;

    @ApiOperation(value = "系统通知列表")
    @PostMapping("/comment/page")
    @WebLog(description = "系统通知列表")
    public Result<?> page(@ApiParam(name = "OfficialNotificationDto", value = "系统通知请求参数", required = true)
                              @RequestBody OfficialNotificationDto dto) {
        UserInfoVo userInfoVo = UserContext.getUser();
        if (userInfoVo == null){
            return Result.fail("用户未登录");
        }
        Page<OfficialNotification> pageParam = new Page<>(dto.getPage(), dto.getLimit());
        IPage<OfficialNotification> page = officialNotificationService.selectPage(pageParam,dto);
        return Result.ok(page);
    }
    // ========== 新增通知 ==========
    @ApiOperation("新增系统通知")
    @PostMapping("/add")
    @WebLog(description = "新增系统通知")
    public Result<?> add(@ApiParam(name = "OfficialNotification", value = "通知内容", required = true)
                         @Valid @RequestBody OfficialNotification notification) {
        boolean success = officialNotificationService.saveNotification(notification);
        return success ? Result.ok() : Result.fail("新增失败");
    }

    // ========== 修改通知 ==========
    @ApiOperation("修改系统通知")
    @PostMapping("/update")
    @WebLog(description = "修改系统通知")
    public Result<?> update(@ApiParam(name = "OfficialNotification", value = "通知内容", required = true)
                            @Valid @RequestBody OfficialNotification notification) {

        boolean success = officialNotificationService.updateNotificationById(notification);
        return success ? Result.ok() : Result.fail("修改失败");
    }

    // ========== 删除通知 ==========
    @ApiOperation("删除系统通知")
    @PostMapping("/delete/{id}")
    @WebLog(description = "删除系统通知")
    public Result<?> delete(@ApiParam(name = "id", value = "通知ID", required = true)
                            @PathVariable Long id) {
        boolean success = officialNotificationService.deleteNotificationById(id);
        return success ? Result.ok() : Result.fail("删除失败");
    }
    @ApiOperation("广播官方通知")
    @PostMapping("/broadcast")
    @WebLog(description = "广播系统通知")
    public Result<?> broadcast(@ApiParam(name = "OfficialNotification", value = "通知内容", required = true)
                               @Valid @RequestBody OfficialNotification notification) {
        webSocketBroadcastService.broadcastOfficialNotification(String.valueOf(notification.getId()));
        return Result.ok();
    }

    @ApiOperation("取消官方通知")
    @PostMapping("/cancelOfficialNotice/{id}")
    @WebLog(description = "取消官方通知")
    public Result<?> cancelOfficialNotice(@ApiParam(name = "id", value = "通知id", required = true)
                                          @PathVariable Long id){
        return officialNotificationService.cancelOfficialNotice(id);

    }

    @ApiOperation("上传活动页")
    @PostMapping("/uploadActivity")
    @WebLog(description = "上传活动页")
    public Result<?> uploadActivity(@RequestParam("file") MultipartFile file){
        if (file == null){
            return Result.fail("上传文件为空");
        }
        // 获取文件后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        }

        // 校验后缀只能是 .html
        if (!".html".equals(suffix)) {
            return Result.fail("只能上传 HTML 文件");
        }



        try {
            Path uploadPath = Paths.get(activityPath);
            if (!Files.exists(uploadPath)){
                Files.createDirectories(uploadPath);
            }
            String fileName = System.currentTimeMillis() + "_" + originalFilename;
            Path filePath = uploadPath.resolve(fileName);
            Files.copy(file.getInputStream(),filePath);
            FilePathVo filePathVo = new FilePathVo();
            filePathVo.setActivityPath(filePath.toString());
            filePathVo.setFileName(fileName);
            filePathVo.setActivityUrl(activityUrlPrefix + fileName);


            return Result.ok(filePathVo);
        }catch (IOException e){
            e.printStackTrace();
            return Result.fail("上传文件失败");
        }

    }
}
